package com.supeng.PMdepot.activity;

import android.content.DialogInterface;
import android.os.Bundle;
import android.support.v7.app.AlertDialog;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.text.InputType;
import android.text.TextUtils;
import android.text.method.ScrollingMovementMethod;
import android.view.KeyEvent;
import android.view.MotionEvent;
import android.view.View;
import android.view.ViewGroup;
import android.view.WindowManager;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.chad.library.adapter.base.BaseQuickAdapter;
import com.supeng.PMdepot.ItemDecoration.SpaceItemDecoration;
import com.supeng.PMdepot.R;
import com.supeng.PMdepot.adapter.PaiGongDanAdapter;
import com.supeng.PMdepot.base.BaseActivity;
import com.supeng.PMdepot.common.Constant;
import com.supeng.PMdepot.entity.ChukuInfo;
import com.supeng.PMdepot.entity.PaiGongBeen;
import com.supeng.PMdepot.entity.PaiGongGetInfo;
import com.supeng.PMdepot.entity.ServiceResult;
import com.supeng.PMdepot.net.Api;
import com.supeng.PMdepot.net.NetUtils;
import com.supeng.PMdepot.util.ToastUtils;

import java.util.List;

import butterknife.BindView;
import butterknife.ButterKnife;

public class ChukuActivity extends BaseActivity {


    @BindView(R.id.iv_back)
    ImageView ivBack;
    @BindView(R.id.tv_title)
    TextView tvTitle;
    @BindView(R.id.title_bar)
    RelativeLayout titleBar;
    @BindView(R.id.et_kucun)
    EditText etKucun;
    @BindView(R.id.vv_blue2)
    View vvBlue2;
    @BindView(R.id.tv_cpname)
    TextView tvCpname;
    @BindView(R.id.tv_pgCount)
    TextView tvPgCount;
    @BindView(R.id.lyCount)
    TextView lyCount;
    @BindView(R.id.vv_blue3)
    View vvBlue3;
    @BindView(R.id.rv_list)
    RecyclerView rvList;
    @BindView(R.id.root_layout)
    LinearLayout rootLayout;
    public String paigongdan;
    public String chanpin;
    @BindView(R.id.tv_pgdh)
    TextView tvPgdh;
    @BindView(R.id.tv_count)
    TextView tvCount;
    private PaiGongDanAdapter homeAdapter;
    private int dailingyong = 0;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        //弹出键盘滚动问题
        getWindow().setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_ADJUST_PAN);
        setContentView(R.layout.activity_chuku);
        unbinder = ButterKnife.bind(this);
        initView();
        initData();
        initAdapter();
    }

    private boolean actionOk(TextView v) {
        if (!TextUtils.isEmpty(chanpin)) {
            etKucun.setText("");
            ToastUtils.show("请等待上一个条码入库才可以进行下一条码扫描");
            return true;
        }
        String search = v.getText().toString();
        etKucun.setText("");
        if (TextUtils.isEmpty(search)) {
            ToastUtils.show("无效二维码");
            return true;
        }
        if (TextUtils.isEmpty(paigongdan)) {
            //派工二维码
            if (search.indexOf(Constant.PaiGongDanKey) == 0) {
                paigongdanGet(search);
            } else {
                ToastUtils.show("请先扫描派工单号");
                return true;
            }
        } else {
            if (search.indexOf(Constant.PaiGongDanKey) == 0) {
                paigongdanGet(search);
            } else {
                //产品二维码
                if (search.indexOf(Constant.ChanPinKey) == 0) {
                    chanpin = search;
                    if (!TextUtils.isEmpty(chanpin) && !TextUtils.isEmpty(paigongdan)) {
                        doAddServer(chanpin, paigongdan);
                    }
                } else {
                    ToastUtils.show("无效二维码");
                    return true;
                }
            }
        }
        return false;
    }

    private void paigongdanGet(String search) {
        paigongdan = search;
        tvPgdh.setText(search);
        doSearchServer(search);
    }

    private void doAddServer(final String mchanpin, final String paigongdan) {
        Api.storageOut(getActivity(), mchanpin, paigongdan, new NetUtils.NetCallBack<ServiceResult>() {
            @Override
            public void success(ServiceResult rspData) {
                if (rspData.getRecode() == 1) {
                    ChukuInfo chukuInfo = (ChukuInfo) rspData;
                    PaiGongBeen chukuBeen = chukuInfo.getInfo();
                    chukuBeen.setGongdan(paigongdan);
                    List<PaiGongBeen> rukuBeens = homeAdapter.getData();
                    for (PaiGongBeen rukuBeent : rukuBeens) {
                        if (rukuBeent.getCptiaoma().equals(mchanpin)) {
                            //todo server OK
                            chanpin = "";
                            ToastUtils.show("条码已录入");
                            return;
                        }
                    }
                    homeAdapter.addData(0, chukuBeen);
                    homeAdapter.notifyItemChanged(0);
                    rvList.smoothScrollToPosition(0);
                    setLyCount();
                    //todo server OK
                    chanpin = "";
                } else {
                    chanpin = "";
                    ToastUtils.show(rspData.getMsg());
                }
            }

            @Override
            public void failed(String msg) {
                chanpin = "";
                ToastUtils.show(msg);
            }

            @Override
            public void onUsedCache(String msg) {

            }
        }, ChukuInfo.class);

    }

    private void setLyCount() {
        List<PaiGongBeen> rukuBeens = homeAdapter.getData();
        int allly = 0;
        for (PaiGongBeen rukuBeent : rukuBeens) {
            if (rukuBeent.getGongdan().equals(paigongdan)) {
                allly += rukuBeent.getShuliang();
            }
        }
        lyCount.setText((dailingyong - allly) + "");
        tvCount.setText("数量:" + homeAdapter.getData().size());
    }

    public void clearPaiGongXinxi() {
        tvPgCount.setText("");
        tvPgdh.setText("");
        tvCpname.setText("");
        lyCount.setText("");
        dailingyong = 0;
    }

    //查找派工单信息
    private void doSearchServer(String serach) {
        Api.searchPaigong(getActivity(), serach, new NetUtils.NetCallBack<ServiceResult>() {
            @Override
            public void success(ServiceResult rspData) {
                if (rspData.getRecode() == 1) {
                    PaiGongGetInfo paiGongGetInfo = (PaiGongGetInfo) rspData;
                    PaiGongGetInfo.InfoBean infoBean = paiGongGetInfo.getInfo();
                    tvPgCount.setText(infoBean.getAllCount() + "");
                    tvPgdh.setText(paigongdan + "");
                    tvCpname.setText(infoBean.getCpName() + infoBean.getCpXinghao());
                    dailingyong = (infoBean.getAllCount() - infoBean.getDaipaigongCount());
                    lyCount.setText(dailingyong + "");
                } else {
                    ToastUtils.show(rspData.getMsg());
                    clearPaiGongXinxi();
                }
            }

            @Override
            public void failed(String msg) {
                ToastUtils.show(msg);
                clearPaiGongXinxi();
            }

            @Override
            public void onUsedCache(String msg) {

            }
        }, PaiGongGetInfo.class);


    }

    private void initData() {

        etKucun.setOnEditorActionListener(new TextView.OnEditorActionListener() {
            @Override
            public boolean onEditorAction(TextView v, int actionId, KeyEvent event) {

                if (actionId == 0 || actionId == 6) {
                    if (event == null) {

                        if (actionOk(v)) return true;
                    } else {
                        switch (event.getAction()) {
                            case KeyEvent.ACTION_UP:

                                if (actionOk(v)) return true;
                        }
                    }
                }
                return true;

            }
        });

    }

    private void initAdapter() {

        rvList.setLayoutManager(new LinearLayoutManager(getActivity()));
        rvList.addItemDecoration(new SpaceItemDecoration(getActivity()).setSpace(0.5f).setSpaceColor(getResources().getColor(R.color.item_press2)));
        homeAdapter = new PaiGongDanAdapter();
        homeAdapter.setOnItemChildClickListener(new BaseQuickAdapter.OnItemChildClickListener() {
            @Override
            public void onItemChildClick(BaseQuickAdapter adapter, View view, int position) {
                switch (view.getId()) {
                    case R.id.tv_name:
                        break;
                }
            }
        });
        homeAdapter.setOnItemLongClickListener(new BaseQuickAdapter.OnItemLongClickListener() {
            @Override
            public boolean onItemLongClick(BaseQuickAdapter adapter, View view, final int position) {
                final PaiGongBeen paiGongBeen = (PaiGongBeen) adapter.getData().get(position);
                AlertDialog dialog = new AlertDialog.Builder(getActivity())
                        .setTitle("是否删除产品编号" + paiGongBeen.getCptiaoma() + "这条记录")
                        .setNegativeButton("是", new DialogInterface.OnClickListener() {
                            @Override
                            public void onClick(DialogInterface dialog, int which) {
                                doDelete(paiGongBeen, position);
                                dialog.dismiss();
                            }
                        })
                        .setPositiveButton("否", new DialogInterface.OnClickListener() {
                            @Override
                            public void onClick(DialogInterface dialog, int which) {
                                dialog.dismiss();
                            }
                        })
                        .show();
                return false;
            }
        });
        homeAdapter.setOnItemClickListener(new BaseQuickAdapter.OnItemClickListener() {
            @Override
            public void onItemClick(BaseQuickAdapter adapter, View view, final int position) {

            }
        });
        homeAdapter.setEmptyView(R.layout.loading_view, (ViewGroup) rvList.getParent());
        rvList.setAdapter(homeAdapter);

        homeAdapter.setNewData(null);
    }

    private void doDelete(PaiGongBeen paiGongBeen, int postion) {
        homeAdapter.remove(postion);
        if (paiGongBeen.getGongdan().equals(paigongdan))
            setLyCount();
    }

    private void initView() {
        tvCpname.setMovementMethod(ScrollingMovementMethod.getInstance());
        tvCpname.setHorizontallyScrolling(true);
        etKucun.setOnTouchListener(new View.OnTouchListener() {
            @Override
            public boolean onTouch(View v, MotionEvent event) {
                etKucun.setInputType(InputType.TYPE_CLASS_TEXT);
                return false;
            }
        });
        etKucun.setInputType(InputType.TYPE_NULL);
    }

}
